/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.guobo.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.OperationWebServiceUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.guobo.entity.ExhHall;
import com.thinkgem.jeesite.modules.guobo.entity.Location;
import com.thinkgem.jeesite.modules.guobo.entity.Node;
import com.thinkgem.jeesite.modules.guobo.entity.Rw;
import com.thinkgem.jeesite.modules.guobo.entity.TreeData;
import com.thinkgem.jeesite.modules.guobo.entity.TreeNode;
import com.thinkgem.jeesite.modules.guobo.entity.WarningRole;
import com.thinkgem.jeesite.modules.guobo.service.AssetService;
import com.thinkgem.jeesite.modules.guobo.service.ExhHallService;
import com.thinkgem.jeesite.modules.guobo.service.LocationService;
import com.thinkgem.jeesite.modules.guobo.service.RwService;
import com.thinkgem.jeesite.modules.guobo.service.WarningRoleService;
import com.thinkgem.jeesite.modules.guobo.service.WarnroleRfidService;

import net.sf.json.JSONArray;

/**
 * 读写器Controller
 * @author wudavid
 * @version 2017-03-09
 */
@Controller
@RequestMapping(value = "${adminPath}/guobo/rw")
public class RwController extends BaseController {

	@Autowired
	private RwService rwService;
	
	@Autowired
	private ExhHallService exhHallService;
	
	@Autowired
	private LocationService locationService;
	
	@Autowired
	private WarningRoleService warningRoleService;
	
	@Autowired
	private WarnroleRfidService warnroleRfidService;
	
	@Autowired
	private AssetService assetService;
	
	@ModelAttribute
	public Rw get(@RequestParam(required=false) String id) {
		Rw entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = rwService.get(id);
		}
		if (entity == null){
			entity = new Rw();
		}
		return entity;
	}
	
	@RequiresPermissions("guobo:rw:view")
	@RequestMapping(value = {"list", ""})
	public String list(Rw rw, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Rw> page = rwService.findPage(new Page<Rw>(request, response), rw); 
		model.addAttribute("page", page);
		return "modules/guobo/rwList";
	}

	@RequiresPermissions("guobo:rw:view")
	@RequestMapping(value = "form")
	public String form(Rw rw, Model model) {
		model.addAttribute("rw", rw);
		return "modules/guobo/rwForm";
	}

	@RequiresPermissions("guobo:rw:edit")
	@RequestMapping(value = "save")
	public String save(Rw rw, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, rw)){
			return form(rw, model);
		}
		rwService.save(rw);
		addMessage(redirectAttributes, "保存读写器成功");
		return "redirect:"+Global.getAdminPath()+"/guobo/rw/?repage";
	}
	
	@RequiresPermissions("guobo:rw:edit")
	@RequestMapping(value = "delete")
	public String delete(Rw rw, RedirectAttributes redirectAttributes) {
		rwService.delete(rw);
		addMessage(redirectAttributes, "删除读写器成功");
		return "redirect:"+Global.getAdminPath()+"/guobo/rw/?repage";
	}

	/**
	 * 获取读写器JSON数据
	 * @param response
	 * @return
	 */
	@RequiresPermissions("guobo:rw:edit")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<ExhHall> list = exhHallService.findList(new ExhHall());
		for (int i=0; i<list.size(); i++){
			ExhHall e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", "0");
			map.put("pIds", "0,");
			map.put("name", e.getName());
			map.put("isParent", true);
			mapList.add(map);
			List<Location> locations = locationService.findListByExhHallId(e.getId());
			for (Location location : locations) {
				Map<String, Object> loc = Maps.newHashMap();
				loc.put("id", location.getId());
				loc.put("pId", e.getId());
				loc.put("pIds", e.getId());
				loc.put("name", location.getName());
				loc.put("isParent", true);
				mapList.add(loc);
				List<Rw> rws = rwService.findListByLocation(location.getId());
				for (Rw rw : rws) {
					Map<String, Object> tempRw = Maps.newHashMap();
					tempRw.put("id", rw.getId());
					tempRw.put("pId", location.getId());
					tempRw.put("pIds", location.getId()+","+e.getId());
					tempRw.put("name", rw.getName());
					mapList.add(tempRw);
				}
			}
		}
		return mapList;
	}
	
	
	/**
	 * 位置信息上传
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("guobo:rw:edit")
	@ResponseBody
	@RequestMapping(value = "locationOperation")
	 public Map<String,Object> locationOperation(HttpServletRequest request,HttpServletResponse response, Model model) {
		Map<String,Object> data = new HashMap<String,Object>();		
		String id = request.getParameter("id");
		Rw rw = rwService.get(id);
		List<Rw> rws = new ArrayList<Rw>();
		rws.add(rw);
		data.put("code", "1");
		data.put("msg", "位置信息上传失败");
		try{
			if(id!=null && !"".equals(id) && !"null".equals(id)){
				String result = OperationWebServiceUtils.locationOperation(rws);
				if("0".equals(result)){
					rw.setDispatchStatus("3");
					rwService.save(rw);
					data.put("code", "0");
					data.put("msg", "位置信息上传成功");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return data;
	 }
	
	/**
	 * 布控
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("guobo:rw:edit")
	@ResponseBody
	@RequestMapping(value = "dispatching")
	 public Map<String,Object> dispatching(HttpServletRequest request,HttpServletResponse response, Model model) {
		Map<String,Object> data = new HashMap<String,Object>();		
		String id = request.getParameter("id");
		WarningRole warningRole = warningRoleService.get(id);
		/*Rw temp = warningRole.getRw();
		Rw rw = rwService.get(temp.getId());
		List<String> rwids = new ArrayList<String>();
		rwids.add(warningRole.getRw().getId());
		List<WarnroleRfid> roleRfids = warnroleRfidService.findListByWarnroleId(warningRole.getId(),null);
		List<String> rfids = new ArrayList<String>();
		for (WarnroleRfid wr : roleRfids) {
			String rfid = wr.getRfid();
			Asset asset = assetService.getAssetByRFID(rfid);
			if(asset!=null && "Y".equals(asset.getIsParentRfid()) && !"".equals(asset.getParentRfid())){
				List<Asset> assets = assetService.findAssetsByParentRfid(asset);
				for (Asset ast : assets) {
					rfid = rfid+"-"+ast.getRfid();
				}				
			}
			rfids.add(rfid);
		}
		try {
			if(rwids!=null && rwids.size()>0 && rfids!=null && rfids.size()>0){
				String result = OperationWebServiceUtils.dispatch("YES", rwids, rfids);
				if("0".equals(result)){
					warningRole.setStatus("01");
					rw.setDispatchStatus("1");
					warningRoleService.save(warningRole);
					rwService.save(rw);
					data.put("code", "0");
					data.put("msg", "布控成功");
					return data;
				}else{
					data.put("code", "1");
					data.put("msg", "布控失败");
					return data;
				}
			}
			data.put("code", "1");
			data.put("msg", "布控失败");
			return data;
		} catch (Exception e) {
			e.printStackTrace();
			data.put("code", "1");
			data.put("msg", "布控失败");
			return data;
		}*/
		data.put("code", "1");
		data.put("msg", "布控失败");
		if(warningRole!=null){			
			try {
				String result = warningRoleService.rwDispatch(warningRole);
				if("0".equals(result)){					
					data.put("code", "0");
					data.put("msg", "布控成功");
					return data;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return data;
	 }
	
	/**
	 * 取消布控
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("guobo:rw:edit")
	@ResponseBody
	@RequestMapping(value = "cancelDispatching")
	 public Map<String,Object> cancelDispatching(HttpServletRequest request,HttpServletResponse response, Model model) {
		Map<String,Object> data = new HashMap<String,Object>();
		List<String> rwids = new ArrayList<String>();
		String id = request.getParameter("id");
		rwids.add(id);
		data.put("code", "1");
		data.put("msg", "取消布控失败");
		Rw rw = rwService.get(id);
		try{
			if(id!=null && !"".equals(id) && !"null".equals(id)){
				String result = OperationWebServiceUtils.dispatch("Cancel", rwids, null);
				if("0".equals(result)){
					rw.setDispatchStatus("3");
					rwService.save(rw);
					data.put("code", "0");
					data.put("msg", "取消布控成功");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return data;
	 }
	
	/**
	 * 暂停布控
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("guobo:rw:edit")
	@ResponseBody
	@RequestMapping(value = "pauseDispatching")
	 public Map<String,Object> pauseDispatching(HttpServletRequest request,HttpServletResponse response, Model model) {
		Map<String,Object> data = new HashMap<String,Object>();
		List<String> rwids = new ArrayList<String>();
		String id = request.getParameter("id");
		rwids.add(id);
		data.put("code", "1");
		data.put("msg", "暂停布控失败");
		Rw rw = rwService.get(id);
		try{
			if(id!=null && !"".equals(id) && !"null".equals(id)){
				String result = OperationWebServiceUtils.dispatch("Pause", rwids, null);
				if("0".equals(result)){
					rw.setDispatchStatus("2");
					rwService.save(rw);
					data.put("code", "0");
					data.put("msg", "暂停布控成功");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return data;
	 }
	
	/**
	 * 恢复布控
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("guobo:rw:edit")
	@ResponseBody
	@RequestMapping(value = "resumeDispatching")
	 public Map<String,Object> resumeDispatching(HttpServletRequest request,HttpServletResponse response, Model model) {
		Map<String,Object> data = new HashMap<String,Object>();
		List<String> rwids = new ArrayList<String>();
		String id = request.getParameter("id");
		rwids.add(id);
		data.put("code", "1");
		data.put("msg", "恢复布控失败");
		Rw rw = rwService.get(id);
		try{
			if(id!=null && !"".equals(id) && !"null".equals(id)){
				String result = OperationWebServiceUtils.dispatch("Start", rwids, null);
				if("0".equals(result)){
					rw.setDispatchStatus("1");
					rwService.save(rw);
					data.put("code", "0");
					data.put("msg", "恢复布控成功");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return data;
	 }
	
	/**
	 * 分组的读写器JSON数据
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "treeGroupData")
	public Map<String,Object> treeGroupData(HttpServletRequest request,HttpServletResponse response) {
		String rwIds = request.getParameter("rwIds");
		List<String> ids = new ArrayList<String>();
		if(rwIds!=null && !"".equals(rwIds)){
			ids = Arrays.asList(rwIds.split(",")); 
		}
		Map<String,Object> data = new HashMap<String,Object>();
		List<TreeNode> trees = new ArrayList<TreeNode>();
		List<ExhHall> exhHalls = exhHallService.findList(new ExhHall());
		for (ExhHall exhHall : exhHalls) {
			TreeNode treeNode = new TreeNode();
			treeNode.setId(exhHall.getId());
			treeNode.setText(exhHall.getName());
			treeNode.setState("closed");
			List<Location> locations = locationService.findListByExhHallId(exhHall.getId());			
			List<TreeNode> nodes = new ArrayList<TreeNode>();
			for (Location location : locations) {
				treeNode.setState("open");
				TreeNode locationNode = new TreeNode();
				locationNode.setId(location.getId());
				locationNode.setText(location.getName());
				locationNode.setState("closed");
				List<TreeNode> rwNodes = new ArrayList<TreeNode>();
				List<Rw> rws = rwService.findListByLocation(location.getId());
				for (Rw rw : rws) {
					locationNode.setState("open");
					TreeNode rwNode = new TreeNode();
					rwNode.setId(rw.getId());
					rwNode.setText(rw.getName());
					if(ids!=null && ids.size()>0 && ids.contains(rw.getId())){
						rwNode.setChecked(true);						
					}else{
						rwNode.setChecked(false);
					}
					rwNodes.add(rwNode);
				}
				
				locationNode.setChildren(rwNodes);
				nodes.add(locationNode);
			}
			treeNode.setChildren(nodes);
			trees.add(treeNode);
		}
		data.put("datas", JSONArray.fromObject(trees));
		return data;
	}
	
}